package com.dfbz.filter;

import com.dfbz.service.UserServices;
import com.dfbz.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter("/index.jsp")
public class SignFilter implements Filter {

    private UserServices userServices = new UserServiceImpl();

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        try{
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("uName".equals(cookie.getName())){
                    // 将用户的真实信息查出来
                    Map<String,Object> map = userServices.findUserBaseInfo(cookie.getValue());
                    req.getSession().setAttribute("userBaseInfo", map);
                    resp.sendRedirect(req.getContextPath() + "assets/html/home.jsp");
                    return;
                }
            }
        } catch (Exception e) {

        } finally {
            filterChain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
